<!--
 * @Description: 用户注册组件
 * @Author: hai-27
 * @Date: 2020-02-19 22:20:35
 * @LastEditors: hai-27
 * @LastEditTime: 2020-03-01 15:34:34
 -->
<template>
  <div id="register">
    <el-dialog title="注册" width="300px" center :visible.sync="isRegister">
      <el-form
        :model="RegisterUser"
        :rules="rules"
        status-icon
        ref="ruleForm"
        class="demo-ruleForm"
      >
		<el-form-item prop="userName">
		  <el-input
		    prefix-icon="el-icon-user"
		    placeholder="请输入昵称"
		    v-model="RegisterUser.userName"
		  ></el-input>
		</el-form-item>
        <el-form-item prop="name">
          <el-input
            prefix-icon="el-icon-user-solid"
            placeholder="请输入账号"
            v-model="RegisterUser.name"
          ></el-input>
        </el-form-item>
		
		<el-form-item prop="email">
		  <el-input
		    prefix-icon="el-icon-s-cooperation"
		    placeholder="请输入邮箱"
		    v-model="RegisterUser.email"
		  ></el-input>
		</el-form-item>
		<el-form-item prop="emailcode">
		  <el-col :span="13">
		  <el-input
		    prefix-icon="el-icon-s-comment"
		    placeholder="邮箱验证码"
		    v-model="RegisterUser.emailcode"
		  ></el-input>
			</el-col>
			<el-col :span="2">
			  <el-button @click="sendCode" type="primary" :disabled="canClick" style="width: 120px;" size="medium">{{btnText}}</el-button>
			</el-col>
		</el-form-item>
		
		
        <el-form-item prop="pass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请输入密码"
            v-model="RegisterUser.pass"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请再次输入密码"
            v-model="RegisterUser.confirmPass"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" @click="Register" style="width:100%;">注册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {sendEmail,checkEmailCode,checkUser,registerUser} from '@/api/register.js'
export default {
  name: "MyRegister",
  props: ["register"],
  data() {
	
	            /**
             * 邮箱校验
             * */
            var checkEmail = (rule, value, callback) => {
                const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
                if (!value) {
                    return callback(new Error('邮箱不能为空'))
                }
                setTimeout(() => {
                    if (mailReg.test(value.trim())) {
                    callback()
                } else {
                    callback(new Error('请输入正确的邮箱格式'))
                }
            }, 100)
            };
			
			/**
			 * 昵称校验
			 * */
			var checkUserName = (rule, value, callback) => {
			    if (value==="") {
			        return callback(new Error("请输入昵称"));
			    }else{
					this.$refs.ruleForm.validateField("checkPass");
					return callback();
				}
			};
	
	// 邮箱验证码的校验方法
	let validateEmailCode = (rule, value, callback) => {
	  if (!value) {
	    return callback(new Error("请输入验证码"));
	  }
	  if(this.RegisterUser.email==''){
		  return
	  }
		var params={email:this.RegisterUser.email,code:this.RegisterUser.emailcode}
		checkEmailCode(params).then(res=>{
					if (res.data.code == 1) {
					  this.$refs.ruleForm.validateField("checkPass");
					  return callback();
					} else {
					  return callback(new Error(res.data.message));
					}
		}).catch(err => {
		  return Promise.reject(err);
		})

	};
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
      if (userNameRule.test(value)) {
		 //判断数据库中是否已经存在该用户名
		var params={account:this.RegisterUser.name}
		checkUser(params).then(res=>{
			// “1”代表用户名不存在，可以注册
					if (res.data.code == 1) {
					  this.$refs.ruleForm.validateField("checkPass");
					  return callback();
					} else {
					  return callback(new Error(res.data.message));
					}
		}).catch(err => {
		  return Promise.reject(err);
		})
      } else {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z]\w{5,17}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    // 确认密码的校验方法
    let validateConfirmPass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入确认密码"));
      }
      // 校验是否以密码一致
      if (this.RegisterUser.pass != "" && value === this.RegisterUser.pass) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("两次输入的密码不一致"));
      }
    };
    return {
	//发送验证码
      btnText:"发送验证码",
      canClick: false,
      totalTime: 30,
      isRegister: false, // 控制注册组件是否显示
      RegisterUser: {
		userName:"", //昵称
        name: "", //账号
        pass: "",
        confirmPass: "",
		email:"",
		emailcode:""
      },
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        name: [{ validator: validateName, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        confirmPass: [{ validator: validateConfirmPass, trigger: "blur" }],
		email: [{ validator: checkEmail, trigger: "blur" }],
		emailcode: [{ validator: validateEmailCode, trigger: "blur" }],
		userName: [{ validator: checkUserName, trigger: "blur" }]
      }
    };
  },
  watch: {
    // 监听父组件传过来的register变量，设置this.isRegister的值
    register: function(val) {
      if (val) {
        this.isRegister = val;
      }
    },
    // 监听this.isRegister变量的值，更新父组件register变量的值
    isRegister: function(val) {
      if (!val) {
        this.$refs["ruleForm"].resetFields();
        this.$emit("fromChild", val);
      }
    }
  },
  methods: {
	  	 /** 获取验证码 */
    sendCode(){
	  if(this.RegisterUser.email==''){
		  return
	  }
	  var params={setTo:this.RegisterUser.email}
	  sendEmail(params).then(res=>{
			console.log(res)
	  }).catch(err => {
	    return Promise.reject(err);
	  })
	  
	  
      if (this.canClick) return
      this.canClick = true
      this.btnText = this.totalTime + 's后重新发送'
      let clock = window.setInterval(()=> {
        this.totalTime--
        this.btnText = this.totalTime + 's后重新发送'
        if (this.totalTime < 0){
          window.clearInterval(clock)
          this.btnText = '重新发送验证码'
          this.totalTime = 30
          this.canClick = false
        }
      },1000)
    },
    Register() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs["ruleForm"].validate(valid => {
        //如果通过校验开始注册
        if (valid) {
			var params={
				userName:this.RegisterUser.userName,
				account:this.RegisterUser.name,
				password:this.RegisterUser.pass,
				email:this.RegisterUser.email
			}
			registerUser(params).then(res=>{
				// “1”代表注册成功，其他的均为失败
				if (res.data.code === 1) {
				  // 隐藏注册组件
				  this.isRegister = false;
				  // 弹出通知框提示注册成功信息
				  this.notifySucceed(res.data.message);
				} else {
				  // 弹出通知框提示注册失败信息
				  this.notifyError(res.data.message);
				}
			}).catch(err => {
			  return Promise.reject(err);
			})
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style>
</style>